import os
import numpy as np
import json
import logging
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.options
from tornado.options import define, options
from tornado.escape import json_decode
import time


from pdf_png import pdf_png
from content import content


define("port", type=int, default=8999)

# logger and level
logger = logging.getLogger(__name__)
logging.getLogger().setLevel(logging.WARNING)


class IndexHandler(tornado.web.RequestHandler):

    # health check requires
    def head(self):
        self.set_status(200)

    # none
    def get(self, *args, **kwargs):
        self.set_status(200)

    # business method
    def post(self, *args, **kwargs):
        start = time.time()
        self.set_header('Access-Control-Allow-Origin', '*')
        #
        self.set_header('Access-Control-Allow-Methods',
                        'POST, GET, OPTIONS, HEAD')

        pdf_file = self.request.files.get('pdf_file')#获取pdf_file列表对象
        pdf_bytes = pdf_file[0]['body'] #pdf_file转换为二进制流
        imgs = pdf_png(pdf_bytes)
        result = predicts(imgs)

        self.set_header('Content-Type', 'application/json; charset=UTF-8')
        self.write(json.dumps(result))
        self.finish()

def predicts(input_image):
    try:
        start = time.time()
        dic_content = content(input_image)
        result_obj = {
            'code': 0,
            'msg': 'ok',
            'content': dic_content
        }
        logger.warning('[predicts-cost-time]-' +
                       str(round((time.time()-start)*1000)))
        logger.warning(result_obj)
        return result_obj
    except Exception as err:
        result_obj = {
            'code': 1,
            'msg': str(err),
            'possible': float(0.0)
        }
        return result_obj


class CustomApplication(tornado.web.Application):
    def __init__(self, urls, configs):
        handlers = urls
        settings = configs
        super(CustomApplication, self).__init__(handlers=handlers, **settings)


def main():
    urls = [(r"/", IndexHandler)]
    configs = dict(debug=False)
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(
        CustomApplication(urls, configs))
    http_server.listen(options.port)
    # http_server.start(0)
    tornado.ioloop.IOLoop.instance().start()


if __name__ == "__main__":
    # pre process
  
    logger.warning("service started at:" + str(options.port))
    main()
